package org.lex.game.sudoku.view.solver;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

import javax.swing.JLabel;

import org.lex.game.sudoku.model.solver.Decision;
import org.lex.game.sudoku.model.solver.SolverObserver;

public class LabelSolverObserver extends JLabel implements SolverObserver {
	private static final long serialVersionUID = -4256194533107135207L;
	private Deque<Decision> decisions = new ArrayDeque<>();

	public LabelSolverObserver() {
		super();
		initialize();
	}

	private void initialize() {
		this.setText("0 Decisions");
		this.decisions.clear();
	}

	@Override
	public void beginDecision(Decision d) {
		this.decisions.addLast(d);
		this.updateDecisions();
	}

	@Override
	public void fillCell(int row, int col, int num) {
	}

	@Override
	public void rollbackDecision(Decision d, int cellCount) {
		this.decisions.removeLast();
		this.updateDecisions();
	}

	@Override
	public void reset() {
		this.initialize();
	}

	private void updateDecisions() {
		StringBuilder buf = new StringBuilder();
		buf.append(this.decisions.size()).append(" Decisions: ");
		for (Iterator<Decision> iter = this.decisions.iterator(); iter.hasNext();) {
			Decision d = iter.next();
			buf.append('(').append(d.row + 1).append(',').append(d.column + 1).append(")=").append(d.number);
			if (iter.hasNext()) {
				buf.append("-> ");
			}
		}
		this.setText(buf.toString());
	}

}
